package com.qyhl.cloud.webtv.module_integral.wallet.cash;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.provider.Settings;
import android.text.style.TextAppearanceSpan;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.google.android.material.snackbar.Snackbar;
import com.gyf.immersionbar.ImmersionBar;
import com.qyhl.cloud.webtv.module_integral.R;
import com.qyhl.cloud.webtv.module_integral.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.SpanUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.intergral.AccountBean;
import com.qyhl.webtv.commonlib.entity.intergral.CashLimitBean;
import com.qyhl.webtv.commonlib.entity.intergral.IntegralUserInfoBean;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.GridDividerItemDecoration;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import es.dmoral.toasty.Toasty;

@Route(path = ARouterPathConstant.PUTFORWARD)
public class CashActivity extends BaseActivity implements CashContract.CashView {
    @BindView(R2.id.cash_title)
    TextView cashTitle;
    @BindView(R2.id.cash_toolbar)
    Toolbar cashToolbar;
    @BindView(R2.id.cash_current)
    TextView cashCurrent;
    @BindView(R2.id.cash_style_radioGroup)
    RadioGroup cashStyleRadioGroup;
    @BindView(R2.id.cash_account_set)
    TextView cashAccountSet;
    @BindView(R2.id.cash_recyclerView)
    RecyclerView cashRecyclerView;
    @BindView(R2.id.cash_tip1)
    TextView cashTip1;
    @BindView(R2.id.cash_tip2)
    TextView cashTip2;
    @BindView(R2.id.cash_tip4)
    TextView cashTip4;
    @BindView(R2.id.root_layout)
    RelativeLayout rootLayout;
    @BindView(R2.id.cash_tip3)
    TextView cashTip3;
    @BindView(R2.id.cash_num_card)
    CardView cashNumCard;
    @BindView(R2.id.cash_style_wechat)
    RadioButton cashStyleWechat;

    private CommonAdapter commonAdapter;
    private List<CashNumBean> mDataList = new ArrayList<>();

    private String alipayName;//支付宝用户名

    private String alipayAccount;//支付宝账户

    private boolean isAlipay = true;

    private String weChatName;//微信用户名

    private String weChatOpenId;//微信openid

    private static final int ALIPAY_CODE = 1;

    private static final int WECHAT_CODE = 2;

    private CashPresenter mPresenter;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected int getContentView() {
        return R.layout.inter_activity_cash;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        initCash();
        mPresenter = new CashPresenter(this);
        setLisenter();
        mPresenter.getCashLimit();
    }

    @Override
    protected void setListener() {

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (android.R.id.home == item.getItemId()) {
            onBackPressed();
            return true;
        } else if (item.getItemId() == R.id.cash_charge) {
            RouterManager.router(ARouterPathConstant.EXCHANGE_GOLD);
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.cash_exchange_menu, menu);
        return true;

    }

    private void initCash() {
        cashStyleWechat.setVisibility(View.GONE);//不支持微信绑定
        alipayName = Objects.requireNonNull(getIntent().getExtras()).getString("alipayName", "");
        alipayAccount = getIntent().getExtras().getString("alipayAccount", "");
        Double curMoney = getIntent().getExtras().getDouble("currMoney", 0.00);

        weChatName = getIntent().getExtras().getString("wxName", "");
        weChatOpenId = getIntent().getExtras().getString("wxOpenid", "");

        cashTitle.setText("我要提现");
        cashCurrent.setText(curMoney + "");

        cashStyleRadioGroup.check(R.id.cash_style_alipay);
        setDefaultData();
        setAlipay();

        setSupportActionBar(cashToolbar);


        cashRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        cashRecyclerView.addItemDecoration(new GridDividerItemDecoration(30, getResources().getColor(R.color.white)));
        cashRecyclerView.setAdapter(commonAdapter = new CommonAdapter<CashNumBean>(this, R.layout.inter_item_cash_num, mDataList) {

            @Override
            protected void convert(ViewHolder viewHolder, CashNumBean cashNumBean, int i) {
                TextView textView = viewHolder.getView(R.id.cash_num);
                textView.setText(cashNumBean.getCashNum() + "元");

                if (cashNumBean.isClick()) {
                    textView.setTextColor(getResources().getColor(R.color.global_base));
                    textView.setBackgroundResource(R.drawable.cash_chose_bg_on);
                } else {
                    textView.setTextColor(getResources().getColor(R.color.global_black_lv1));
                    textView.setBackgroundResource(R.drawable.cash_chose_bg_off);
                }
            }
        });

    }

    /**
     * 设置默认数据
     */
    private void setDefaultData() {
        mDataList.clear();
        mDataList.add(new CashNumBean(1, true));
        mDataList.add(new CashNumBean(5, false));
        mDataList.add(new CashNumBean(10, false));
        mDataList.add(new CashNumBean(30, false));
        mDataList.add(new CashNumBean(50, false));
        mDataList.add(new CashNumBean(100, false));
        mDataList.add(new CashNumBean(500, false));
    }

    /**
     * 设置阿里支付信息
     */
    private void setAlipay() {

        isAlipay = true;
        if (StringUtils.isEmpty(alipayAccount) || StringUtils.isEmpty(alipayName)) {
            cashAccountSet.setText("设置支付宝账号");
            cashAccountSet.setTextColor(getResources().getColor(R.color.global_base));
            Drawable rightDrawable = getResources().getDrawable(R.drawable.cash_set_off_icon);
            cashAccountSet.setCompoundDrawablesWithIntrinsicBounds(null, null, rightDrawable, null);
        } else {
            Drawable rightDrawable = getResources().getDrawable(R.drawable.cash_set_on_icon);
            Drawable leftDrawable = getResources().getDrawable(R.drawable.cash_set_alipay_icon);
            cashAccountSet.setCompoundDrawablesWithIntrinsicBounds(leftDrawable, null, rightDrawable, null);
            cashAccountSet.setText(alipayName + "  " + alipayAccount);
            cashAccountSet.setTextColor(getResources().getColor(R.color.global_black_lv1));
        }
        SpanUtils spanUtils = new SpanUtils(this);
        spanUtils.append("1.支付宝申请提现兑换成功后，将在").setSpans(new TextAppearanceSpan(this, R.style.inter_cash_tip_normal2))
                .append("1-3个工作日").setSpans(new TextAppearanceSpan(this, R.style.inter_cash_tip_special))
                .append("（节假日顺延）由客服审核后到账，请耐心等待。").setSpans(new TextAppearanceSpan(this, R.style.inter_cash_tip_normal2));
        cashTip1.setText(spanUtils.create());

        SpanUtils spanUtils2 = new SpanUtils(this);
        spanUtils2.append("2.提现前请确认").setSpans(new TextAppearanceSpan(this, R.style.inter_cash_tip_normal2))
                .append("绑定的支付宝账号").setSpans(new TextAppearanceSpan(this, R.style.inter_cash_tip_special))
                .append("可正常使用。若因支付宝信息有误导致无法提现成功，零钱将返回到“钱包”中。").setSpans(new TextAppearanceSpan(this, R.style.inter_cash_tip_normal));
        cashTip2.setText(spanUtils2.create());

        cashTip3.setText("3.提现到账查询：打开支付宝APP，查看“我的—账单”。");

        cashTip4.setText("注：提现手续费为2%。（即提现1元，实际到账为0.98元，该手续费由支付宝收取）");
    }

    /**
     * 设置微信支付信息
     */
    private void setWeChat() {
        isAlipay = false;
        if (StringUtils.isEmpty(weChatName) || StringUtils.isEmpty(weChatOpenId)) {
            cashAccountSet.setText("设置微信账号");
            cashAccountSet.setTextColor(getResources().getColor(R.color.global_base));
            Drawable rightDrawable = getResources().getDrawable(R.drawable.cash_set_off_icon);
            rightDrawable.setBounds(0, 0, rightDrawable.getMinimumWidth(), rightDrawable.getMinimumHeight());
            cashAccountSet.setCompoundDrawablesWithIntrinsicBounds(null, null, rightDrawable, null);
        } else {
            Drawable rightDrawable = getResources().getDrawable(R.drawable.cash_set_on_icon);
            rightDrawable.setBounds(0, 0, rightDrawable.getMinimumWidth(), rightDrawable.getMinimumHeight());
            Drawable leftDrawable = getResources().getDrawable(R.drawable.cash_set_wechat_icon);
            leftDrawable.setBounds(0, 0, rightDrawable.getMinimumWidth(), rightDrawable.getMinimumHeight());
            cashAccountSet.setCompoundDrawablesWithIntrinsicBounds(leftDrawable, null, rightDrawable, null);
            cashAccountSet.setTextColor(getResources().getColor(R.color.global_black_lv1));
            cashAccountSet.setText(weChatName);
        }

        SpanUtils spanUtils = new SpanUtils(this);
        spanUtils.append("1.微信提现兑换成功后，将在").setSpans(new TextAppearanceSpan(this, R.style.inter_cash_tip_normal2))
                .append("1-3个工作日").setSpans(new TextAppearanceSpan(this, R.style.inter_cash_tip_special))
                .append("（节假日顺延）由客服审核后到账，请耐心等待；").setSpans(new TextAppearanceSpan(this, R.style.inter_cash_tip_normal2));
        cashTip1.setText(spanUtils.create());

        SpanUtils spanUtils2 = new SpanUtils(this);
        spanUtils2.append("2.").setSpans(new TextAppearanceSpan(this, R.style.inter_cash_tip_normal2))
                .append("兑换时请填写真实姓名且确保微信已进行实名认证。").setSpans(new TextAppearanceSpan(this, R.style.inter_cash_tip_special))
                .append("如因提现资料有误导致无法充值费用将原路返回；").setSpans(new TextAppearanceSpan(this, R.style.inter_cash_tip_normal2));
        cashTip2.setText(spanUtils2.create());

        cashTip3.setText(getResources().getString(R.string.cash_wechat_tip_three));

        cashTip4.setText("4.提现到账查询：微信->我的->账单，如果有名为‘" + getResources().getString(R.string.app_name) + "提现成功’的数据，即为提现成功到账；");

    }

    private void setLisenter() {
        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int position) {
                for (int i = 0; i < mDataList.size(); i++) {
                    if (position == i) {
                        mDataList.get(i).setClick(true);
                    } else {
                        mDataList.get(i).setClick(false);
                    }
                }
                commonAdapter.notifyDataSetChanged();
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                return false;
            }
        });

        cashStyleRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                if (i == R.id.cash_style_alipay) {
                    setAlipay();
                } else {
                    setWeChat();
                }
            }
        });
    }

    @OnClick({R2.id.cash_commit, R2.id.cash_account_set})
    public void onViewClicked(View view) {
        int i1 = view.getId();
        if (i1 == R.id.cash_commit) {
            int money = 0;
            for (int i = 0; i < mDataList.size(); i++) {
                if (mDataList.get(i).isClick()) {
                    money = mDataList.get(i).getCashNum();
                }
            }
            if (money == 0) {
                Toasty.normal(this, "系统维护，暂时无法提现！").show();
                return;
            }
            int i = cashStyleRadioGroup.getCheckedRadioButtonId();
            if (i == R.id.cash_style_alipay) {
                if (StringUtils.isNotEmpty(alipayAccount) && StringUtils.isNotEmpty(alipayName)) {
                    showSimpleLoading();
                    String userName = CommonUtils.getInstance().getUserName();
                    mPresenter.doCommit(userName, money, "1");
                } else {
                    Toasty.normal(this, "未绑定支付宝或绑定信息不完整！").show();
                }
            } else if (i == R.id.cash_style_wechat) {
                if (StringUtils.isNotEmpty(weChatName) && StringUtils.isNotEmpty(weChatOpenId)) {
                    String userName = CommonUtils.getInstance().getUserName();
                    showSimpleLoading();
                    mPresenter.doCommit(userName, money, "2");
                    ActionLogUtils.getInstance().onEvent(ActionConstant.PUTFORWARD);
                } else {
                    Toasty.normal(this, "未绑定微信或绑定信息不完整！").show();
                }

            } else {
                Toasty.normal(this, "请选择提现方式！").show();

            }

        } else if (i1 == R.id.cash_account_set) {
            if (isAlipay) {
                Bundle bundle = new Bundle();
                bundle.putString("account", alipayAccount.trim());
                bundle.putString("name", alipayName.trim());
                RouterManager.router(this,ARouterPathConstant.BIND_ALIPAY,bundle,ALIPAY_CODE);
            } else {
                //微信绑定
            }

        } else {
        }

    }

    @Override
    public void getSuccess(CashLimitBean bean) {
        try {
            mDataList.clear();
            int[] limit = bean.getCashLimit();
            if (limit.length > 0) {
                cashNumCard.setVisibility(View.VISIBLE);
            } else {
                cashNumCard.setVisibility(View.GONE);
            }
            for (int i = 0; i < limit.length; i++) {
                if (i == 0) {
                    mDataList.add(new CashNumBean(limit[i], true));
                } else {
                    mDataList.add(new CashNumBean(limit[i], false));
                }
            }
            commonAdapter.notifyDataSetChanged();
        } catch (Exception e) {
            setDefaultData();
            commonAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void getNetError(String msg) {
        dismissLoading();
        Snackbar.make(rootLayout, msg, Snackbar.LENGTH_LONG).setAction("设置", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(
                                Settings.ACTION_WIFI_SETTINGS),
                        0);
            }
        }).show();
    }

    @Override
    public void getError(String msg) {
        Toasty.normal(this, msg).show();
    }

    @Override
    public void docommitSuccess(AccountBean bean) {
        dismissLoading();
        String userName = CommonUtils.getInstance().getUserName();
        mPresenter.getInfo(userName);
        Toasty.normal(this, "已提交，系统排队处理中！").show();
    }

    @Override
    public void docommitError(String msg) {
        dismissLoading();
        Toasty.normal(this, msg).show();
    }

    @Override
    public void getInfoSuccess(IntegralUserInfoBean bean) {
        cashCurrent.setText(bean.getCurrMoney() + "");
    }

    @Override
    public void getInfoError(String msg) {
        Toasty.normal(this, msg).show();
    }

    class CashNumBean {
        private int cashNum;
        private boolean isClick;

        public CashNumBean(int cashNum) {
            this.cashNum = cashNum;
            this.isClick = false;
        }

        CashNumBean(int cashNum, boolean isClick) {
            this.cashNum = cashNum;
            this.isClick = isClick;
        }

        public int getCashNum() {
            return cashNum;
        }

        public void setCashNum(int cashNum) {
            this.cashNum = cashNum;
        }

        public boolean isClick() {
            return isClick;
        }

        public void setClick(boolean click) {
            isClick = click;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 200) {
            if (requestCode == ALIPAY_CODE) {
                alipayAccount = data.getStringExtra("account");
                alipayName = data.getStringExtra("name");
                setAlipay();
            }

            if (requestCode == WECHAT_CODE) {
                weChatName = data.getStringExtra("name");
                weChatOpenId = data.getStringExtra("id");
                setWeChat();
            }
        }
    }
}
